<template>
  <q-input
    v-model="formatTime"
    filled
    mask="#### - ####"
    :label="field.label"
    @click="popProxy"
  >
    <template v-slot:append>
      <q-icon
        name="event"
        class="cursor-pointer"
      >
        <q-popup-proxy
          ref="qYearProxy"
          transition-show="scale"
          transition-hide="scale"
          v-model="proxyShown"
        >
          <yearpicker color="primary" v-model="selectYear" @change="change" />
        </q-popup-proxy>
      </q-icon>
    </template>
  </q-input>
</template>
<script>
import { defineComponent } from 'vue';
import { date } from 'quasar';
import yearpicker from 'src/components/YearPicker.vue';

export default defineComponent({
  name: 'yearrangeinput',
  components: {
    yearpicker
  },
  props: {
    field: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    const self = this;
    return {
      proxyShown: false,
      begin: '',
      end: '',
      selectYear: '',
      clickCount: 0
    }
  },
  methods: {
    change (val) {
      if (this.proxyShown) {
        if (this.clickCount == 0) {
          this.begin = val;
          this.field.value = `${val}|`
          this.clickCount++;
        } else {
          this.end = val;
          this.field.value = this.begin > this.end ? `${this.end}|${this.begin}` : `${this.begin}|${this.end}`;
          this.$refs.qYearProxy.hide();
          this.clickCount = 0;
        }
      }
    },
    popProxy () {
      this.$refs.qYearProxy.show();
    }
  },
  computed: {
    formatTime: {
      get () {
        if (this.field.value && this.field.value.indexOf('|')) {
          return this.field.value.replace(/\|/, ' - ');
        } else {
          return '';
        }
      },
      set (val) {
        if (val.length === 11) {
          this.field.value = val.split(' - ').join('|');
        }
      }
    }
  },
  mounted () {
    if (this.field.year > 0) {
      const end = date.formatDate(Date.now(), 'YYYY');
      const begin = Number(end) - this.field.year;
      this.field.value = `${begin}|${end}`;
      this.selectYear = begin;
    }
  }
});
</script>
